package net.bwie.realtime.vehicle.job;

import com.alibaba.fastjson.JSON;
import net.bwie.realtime.jtp.common.utils.JdbcUtil;
import net.bwie.realtime.jtp.common.utils.KafkaUtil;
import net.bwie.realtime.vehicle.bean.VehicleData;
import net.bwie.realtime.vehicle.utils.DateTimeUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.HashSet;
import java.util.Set;

/**
 * 实时在线车辆数
 *
 * @Author: FuHe
 * @Date: 2025/5/28
 */
public class VehicleVinCount {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStream<String> kafkaStream = KafkaUtil.consumerKafka(env, "vehicle-date-geohash");
//        kafkaStream.print();
//        DataStream<Integer> vinCountStream = processheadel(kafkaStream);
        DataStream<String> processheadel = processheadel(kafkaStream);
        processheadel.print();
//        JdbcUtil.sinkToClickhouseUpsert(processheadel, "INSERT INTO vehicle_log.vehicle_count (window_start, window_end, vin_count)\n" +
//                "VALUES (?, ?, ?)");


        env.execute("VehicleRealtimeVinCount");
    }

    private static DataStream<String> processheadel(DataStream<String> kafkaStream) {
        SingleOutputStreamOperator<VehicleData> vehicleData = kafkaStream.map(o -> JSON.parseObject(o, VehicleData.class));
        SingleOutputStreamOperator<VehicleData> vehicleDataSingleOutputStreamOperator = vehicleData.assignTimestampsAndWatermarks(WatermarkStrategy
                .<VehicleData>forBoundedOutOfOrderness(Duration.ofSeconds(0))
                .withTimestampAssigner(
                        new SerializableTimestampAssigner<VehicleData>() {
                            @Override
                            public long extractTimestamp(VehicleData element, long recordTimestamp) {
                                return element.getTimestamp();
                            }
                        }
                )
        );
        DataStream<String> process = vehicleDataSingleOutputStreamOperator
                .windowAll(TumblingEventTimeWindows.of(Time.minutes(1)))
                .process(
                        new ProcessAllWindowFunction<VehicleData, String, TimeWindow>() {
                            @Override
                            public void process(Context context, Iterable<VehicleData> elements, Collector<String> out) throws Exception {
                                Set<String> uniqueVins = new HashSet<>();
                                for (VehicleData data : elements) {
                                    if (data.getVin() != null && !uniqueVins.contains(data.getVin())) {
                                        uniqueVins.add(data.getVin());
                                    }
                                }
                                int uniqueCount = uniqueVins.size();
                                // 获取窗口开始时间
                                String windowStart = DateTimeUtil.convertLongToString(context.window().getStart(), DateTimeUtil.DATE_TIME_FORMAT);
                                String windowEnd = DateTimeUtil.convertLongToString(context.window().getEnd(), DateTimeUtil.DATE_TIME_FORMAT);
                                out.collect(windowStart + "," + windowEnd + "," + uniqueCount);
                            }
                        }
                );
        return process;
    }
}
